package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired PurchaseDetailService detailService;
    @Autowired WareSkuService wareSkuService;

    /**
     * 完成采购
     */
    @Override
    @Transactional    //开启事务
    public void done(PurchaseDoneVo doneVo) {
        Long id = doneVo.getId();    //采购单id

        //2、改变采购项(采购需求)的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){    //HASERROR(4, "采购失败")
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else{
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());    //FINISH(3, "已完成")
                //3、将成功采购的进行入库
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());    //查询采购需求信息
                //调用《更新库存》方法         采购商品id           仓库id              采购数量
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }

        detailService.updateBatchById(updates);

        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ?    //flag如果是true, 就设置 FINISH(3, "已完成"), false就设置 HASERROR(4, "采购失败")
                WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }


    /**
     * 领取采购单
     */
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是 新建 或者 已分配 状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
            //过滤：如果是 新建 或者 已分配 状态，才进行处理
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||    //CREATED(0, "新建"
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {    //ASSIGNED(1, "已分配")
                return true;
            }
            return false;
            //处理完，修改状态
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());    //RECEIVE(2, "已领取")
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、改变采购单的状态
        this.updateBatchById(collect);

        //3、改变采购需求的状态
        UpdateWrapper<PurchaseDetailEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("purchase_id", ids);
        PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
        purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());    //BUYING(2, "正在采购")
        detailService.update(purchaseDetailEntity, updateWrapper);
    }


    /**
     * 合并采购需求
     */
    @Override
    @Transactional    //开启事务
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();    //获取采购单id
        //1、如果 采购单id 为空，说明没有采购单，就新建一个
        if(purchaseId == null){
            //新建 采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());    //CREATED(0, "新建")
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //2、合并采购需求
        List<Long> items = mergeVo.getItems();    //获取 合并项集合(要合并的采购需求)
        Long finalPurchaseId = purchaseId;

        List<PurchaseDetailEntity> list = detailService.getBaseMapper().selectBatchIds(items).stream().filter(entity -> {
            //如果是 新建、已分配 或者 采购失败，才可以修改
            return entity.getStatus() < WareConstant.PurchaseDetailStatusEnum.BUYING.getCode() ||    //BUYING(2, "正在采购")
                    entity.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode();    //HASERROR(4, "采购失败")
        }).map(entity -> {
            //修改 采购需求 状态以及采购单id
            entity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());    //ASSIGNED(1, "已分配")
            entity.setPurchaseId(finalPurchaseId);
            return entity;
        }).collect(Collectors.toList());

        detailService.updateBatchById(list);

        //3、合并完后，还要更新 采购单 的信息
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);    //设置采购单id
        purchaseEntity.setUpdateTime(new Date());    //更新时间
        this.updateById(purchaseEntity);
    }


    /**
     * 查询未领取的采购单
     */
    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode())    //CREATED(0, "新建")
                        .or()
                        .eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()));    //ASSIGNED(1, "已分配")
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

}